#include <stdint.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>

#include "render.h"
#include "control_panel.h"
#include "sdl_data.h"
#include "font.h"
#include "parameters.h"
#include "playlist.h"
#include "music.h"
#include "id3.h"

#include <Windows.h>

#define DELAY_TIME 35

void check_music() {
	if (!music_playing()) {
		const char *song = playlist_next();
		retrieve_id3_data(song);
		id3_reset_cycle();
		play_music(song);
	}
}

extern void render_control_panel();

void main_event_loop() {
	uint32_t last_ticks = SDL_GetTicks();

	for (;;) {
		SDL_Event evt;
		while (SDL_PollEvent(&evt)) {
			if (evt.type == SDL_QUIT) return;
			if (evt.type == SDL_MOUSEBUTTONDOWN) {
				SDL_Window *win = SDL_GetWindowFromID(evt.button.windowID);
				if (win == control_window && (SDL_GetWindowFlags(control_window) & SDL_WINDOW_INPUT_FOCUS)) {
					control_mouse_down();
				}
			}
		}

		SDL_GL_MakeCurrent(control_window, control_context);
		font_set_context(1);
		render_control_panel();
		control_render();
		SDL_GL_SwapWindow(control_window);

		SDL_GL_MakeCurrent(main_window, main_context);
		font_set_context(0);
		render();
		SDL_GL_SwapWindow(main_window);

		uint32_t cur_ticks = SDL_GetTicks();
		uint32_t difference = cur_ticks - last_ticks; /* Time for loop */
		uint32_t delay = DELAY_TIME - (difference % DELAY_TIME);

		SDL_Delay(delay);
		last_ticks = cur_ticks;

		check_music();
	}
}